<?php

class memberModel extends RPHP_Model
{

    //检查权限
    public function checkPriv($pv, $return = true, $menu = true)
    {
        $auth = $this->auth->CheckPriv($pv, $return, $menu);
        if ($return) {
            $this->_auth = $auth;
        }

        return $auth;
    }

    public function getDocs($docid)
    {
        if (is_array($docid)) {
            $where = " WHERE `docid` IN (" . implode(",", array_unique($docid)) . ")";
        } else {
            $where = " WHERE `docid`=" . intval($docid);
        }

        $sql = "SELECT `docid`,`filename`,`create_time` FROM {$this->_prefix['primary']}documents " . $where;
        $rs  = $this->sql($sql);
        if ($rs) {
            foreach ($rs as $r) {
                $doc[$r['docid']] = $this->c['doc_host'] . date("Ymd", $r['create_time']) . "/" . date("H", $r['create_time']) . "/" . date("i", $r['create_time']) . "/" . $r['filename'];

            }
            return $doc;
        } else {
            return false;
        }

    }

    

    //获取会员列表
    public function getMemberList($para, $page = 1, $pagesize = 10)
    {

        $where = " ma.`stat`<3 AND ma.`member_type`=1";

        if ($para['stat'] > 0) {
            $where .= " AND ma.`stat`=" . $para['stat'];
        }

        if ($para['pid'] > 0) {
            $where .= " AND ma.`pid`=" . $para['pid'];
        }

        if (isset($para['member_level'])) {
            
            if ($para['member_level'] == -1) {
                $where .= " AND ma.`member_level`=0 AND ma.`mobile`=''";
            } else {
                $where .= " AND ma.`member_level`=" . $para['member_level'] . " AND ma.`mobile`!=''";
            }

        }

        if (isset($para['maker_level'])) {


            $where .= " AND ma.`maker_level`=" . $para['maker_level'];


        }

        if (isset($para['agent_level'])) {

            $where .= " AND ma.`agent_level`=" . $para['agent_level'];
        }

        if ($para['keyword'] != '') {
            if (is_numeric($para['keyword'])) {
                $where .= " AND ma.`mobile`='" . $para['keyword'] . "' OR ma.`recode` = '" . $para['keyword'] . "'";
            } else {
                $where .= " AND ma.`realname` LIKE '%" . $para['keyword'] . "%'  OR ma.`name` = '" . $para['keyword'] . "' ";
            }

        }

        $sql = "SELECT COUNT(ma.`uid`) AS `cnt` FROM {$this->_prefix['primary']}member_account AS ma WHERE " . $where;
        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "ma.`uid` DESC";

            $sql = "SELECT * FROM {$this->_prefix['primary']}member_account AS ma WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
            $rs  = $this->sql($sql);

            if ($rs) {
                foreach ($rs as $k => $r) {

                    $uids[$r['uid']] = $r['uid'];

                    if ($r['pid'] > 0) {
                        $pids[$r['pid']] = $r['pid'];
                    }

                    if ($r['headimgurl'] > 0) {
                        $docids[] = $r['headimgurl'];
                    }

                    if ($r['member_level'] == 0 && $r['mobile'] == "") {
                        $rs[$k]['member_level'] = -1;
                    }
                }
                // 查询推荐人
                if ($pids) {
                    $sql = "SELECT `uid`,`realname`,`recode` FROM {$this->_prefix['primary']}member_account WHERE `uid` IN (" . implode(",", $pids) . ")";
                    $tmp = $this->sql($sql);
                    if ($tmp) {
                        foreach ($tmp as $r) {
                            $parents[$r['uid']] = $r;
                        }
                    }
                }

                // 获取头像
                if ($docids) {
                    $docs = $this->getDocs($docids);
                }

                if ($uids) {

                    // 查询用户资金
                    $sql = "SELECT * FROM {$this->_prefix['primary']}finance_balance WHERE `uid` IN (" . implode(",", $uids) . ")";
                    $tmp = $this->sql($sql);
                    if ($tmp) {
                        foreach ($tmp as $r) {
                            $balance[$r['uid']] = $r;
                        }
                    }

                    // 查询推荐的会员人数
                    $sql = "SELECT COUNT(`uid`) AS `cnt`,`pid` FROM {$this->_prefix['primary']}member_account WHERE `pid` IN (" . implode(",", $uids) . ") AND `stat`<3 GROUP BY `pid`";
                    $tmp = $this->sql($sql);
                    if ($tmp) {
                        foreach ($tmp as $r) {
                            $child[$r['pid']] = $r['cnt'];
                        }
                    }
                }

            }

        }

        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $rs,
            'para'    => $para,
            'parents' => $parents,
            'amount'  => $amount,
            'balance' => $balance,
            'child'   => $child,
            'docs'    => $docs,
        );
    }

    //获取会员列表
    public function exportMemberListCSV($para)
    {
        set_time_limit(0);
        ini_set("memory_limit", '-1');

        $t = time();
        $where = " ma.`stat`<3 AND ma.`member_type`=1";

        if (isset($para['stat']) && $para['stat'] > 0) {
            $where .= " AND ma.`stat`=" . $para['stat'];
        }

        if (isset($para['pid']) && $para['pid'] > 0) {
            $where .= " AND ma.`pid`=" . $para['pid'];
        }

        if (isset($para['member_level'])) {
            if ($para['member_level'] == -1) {
                $where .= " AND ma.`member_level`=0 AND ma.`mobile`=''";
            } else {
                $where .= " AND ma.`member_level`=" . $para['member_level'] . " AND ma.`mobile`!=''";
            }
        }

        if (isset($para['maker_level'])) {
            $where .= " AND ma.`maker_level`=" . $para['maker_level'];
        }

        if (isset($para['agent_level'])) {
            $where .= " AND ma.`agent_level`=" . $para['agent_level'];
        }

        if ($para['keyword'] != '') {
            if (is_numeric($para['keyword'])) {
                $where .= " AND ma.`mobile`='" . $para['keyword'] . "' OR ma.`recode` = '" . $para['keyword'] . "'";
            } else {
                $where .= " AND ma.`realname` LIKE '%" . $para['keyword'] . "%'  OR ma.`name` = '" . $para['keyword'] . "' ";
            }
        }

        $sql = "SELECT ma.uid,ma.recode,ma.mobile,ma.realname,ma.`name`,ma.`create_time`,ma.`member_level`,ma.`pid`,
            ma.`agent_level`,ma.`stat`,ma.`bind_time`,f.money,f.revenue,f.gold_money,f.ximi_money,f.coupon,ticket 
            FROM {$this->_prefix['primary']}member_account AS ma 
            LEFT JOIN {$this->_prefix['primary']}finance_balance AS f ON ma.`uid`=f.`uid` 
            WHERE " . $where . " ORDER BY ma.`uid` DESC";

        $rs  = $this->sql($sql);
        if ($rs) {
            $rs = array_column($rs, null, "uid");

            $sql = "SELECT count(*) as total,pid FROM {$this->_prefix['primary']}member_account AS ma WHERE " . $where . " AND ma.`pid`>0 GROUP BY ma.`pid`";
            $pCnt  = $this->sql($sql);
            $pCnt = $pCnt ? array_column($pCnt, "total", "pid") : [];

            //获取不在父类不在$rs 结果中的集合
            $diff = array_diff_key($pCnt, $rs);
            $pother = [];
            if($diff) {
                $pids_other = array_keys($diff);
                $sql = "SELECT realname,mobile,uid,recode FROM {$this->_prefix['primary']}member_account WHERE uid in (".implode(",", $pids_other).")";
                $pother  = $this->sql($sql);
                $pother = $pother ? array_column($pother, null, "uid") : [];
            }

            $filename = "用户信息".date('Y-m-d H:i',time());
            header('Content-Type:text/csv');
            header("Content-Disposition:attachment;filename={$filename}.csv");
            echo chr(0xEF).chr(0xBB).chr(0xBF);
            ob_end_flush();

            $out = fopen('php://output','w');

            fputcsv($out, array(
                'UID', '邀请码', '手机号码', '会员昵称', '姓名',
                '推荐人', '推荐人邀请码', 'TA的推荐', '注册时间', '会员级别',
                '荣誉级别', '硒豆', '可提现', '金花', '硒米',
                '代金券', '商品票', '状态', '绑定手机时间'
            ));

            foreach( $rs as $v ){

                if ($v['member_level'] == 0 && $v['mobile'] == "") {
                    $v['member_level'] = -1;
                }

                $parent = isset($v[$v['pid']]) ? $v[$v['pid']] : (isset($pother[$v['pid']]) ? $pother[$v['pid']] : []);
                fputcsv($out,[
                    $v['uid'],
                    $v['recode'],
                    $v['mobile'],
                    $v['realname'],
                    $v['name'],
                    $parent['realname'],
                    $parent['recode'],
                    isset($pCnt[$v['uid']]) ? $pCnt[$v['uid']] : 0,
                    date('Y-m-d H:i', $v['create_time']),
                    $this->c['member_level_t'][$v['member_level']],
                    $this->c['honor_level_t'][$v['agent_level']],
                    $v['money'],
                    $v['revenue'],
                    $v['gold_money'],
                    $v['ximi_money'],
                    $v['coupon'],
                    $v['ticket'],
                    $this->c['stat']['normal_t'][$v['stat']],
                    $v['bind_time']>0 ? date("Y-m-d H:i",$v['bind_time']):""
                ]);
            }
            fclose($out);
            die;
        }else {
            header("Content-type: text/html; charset=utf-8");
            echo "没有要导出的数据";
            die;
        }

    }


    //获取会员列表
    public function getExportMemberList($para)
    {
        set_time_limit(0);
        ini_set("memory_limit", '-1');

        $where = " ma.`stat`<3 AND ma.`member_type`=1";

        if ($para['stat'] > 0) {
            $where .= " AND ma.`stat`=" . $para['stat'];
        }

        if ($para['pid'] > 0) {
            $where .= " AND ma.`pid`=" . $para['pid'];
        }

        if (isset($para['member_level'])) {
            if ($para['member_level'] == -1) {
                $where .= " AND ma.`member_level`=0 AND ma.`mobile`=''";
            } else {
                $where .= " AND ma.`member_level`=" . $para['member_level'] . " AND ma.`mobile`!=''";
            }

        }

        if ($para['keyword'] != '') {
            if (is_numeric($para['keyword'])) {
                $where .= " AND ma.`mobile`='" . $para['keyword'] . "' OR ma.`recode` = '" . $para['keyword'] . "'";
            } else {
                $where .= " AND ma.`realname` LIKE '%" . $para['keyword'] . "%'  OR ma.`name` = '" . $para['keyword'] . "' ";
            }

        }
        //默认排序
        $orderby = "ma.`uid` DESC";

        $sql = "SELECT * FROM {$this->_prefix['primary']}member_account AS ma WHERE " . $where . " ORDER BY " . $orderby ;
        $rs  = $this->sql($sql);

        if ($rs) {
            foreach ($rs as $k => $r) {

                $uids[$r['uid']] = $r['uid'];

                if ($r['pid'] > 0) {
                    $pids[$r['pid']] = $r['pid'];
                }


                if ($r['member_level'] == 0 && $r['mobile'] == "") {
                    $rs[$k]['member_level'] = -1;
                }
            }
            // 查询推荐人
            if ($pids) {
                $sql = "SELECT `uid`,`realname`,`recode` FROM {$this->_prefix['primary']}member_account WHERE `uid` IN (" . implode(",", $pids) . ")";
                $tmp = $this->sql($sql);
                if ($tmp) {
                    foreach ($tmp as $r) {
                        $parents[$r['uid']] = $r;
                    }
                }
            }



            if ($uids) {

                // 查询用户资金
                $sql = "SELECT * FROM {$this->_prefix['primary']}finance_balance WHERE `uid` IN (" . implode(",", $uids) . ")";
                $tmp = $this->sql($sql);
                if ($tmp) {
                    foreach ($tmp as $r) {
                        $balance[$r['uid']] = $r;
                    }
                }

                // 查询推荐的会员人数
                $sql = "SELECT COUNT(`uid`) AS `cnt`,`pid` FROM {$this->_prefix['primary']}member_account WHERE `pid` IN (" . implode(",", $uids) . ") AND `stat`<3 GROUP BY `pid`";
                $tmp = $this->sql($sql);
                if ($tmp) {
                    foreach ($tmp as $r) {
                        $child[$r['pid']] = $r['cnt'];
                    }
                }
            }

        }

        return array(

            'data'    => $rs,
            'parents' => $parents,
            'balance' => $balance,
            'child'   => $child,

        );
    }

    public function getMemberData()
    {

        $sql = "SELECT * FROM {$this->_prefix['primary']}member_account  WHERE  `stat`<3 ORDER BY  `uid` DESC";
        $rs  = $this->sql($sql);

        foreach ($rs as $k => $r) {

            $uids[$r['uid']] = $r['uid'];

            if ($r['pid'] > 0) {
                $pids[$r['pid']] = $r['pid'];
            }

            if ($r['member_level'] == 0 && $r['mobile'] == "") {
                $rs[$k]['member_level'] = "用户";
            } else {

                $rs[$k]['member_level'] = strip_tags($this->c['member'][$r['member_level']]);

            }

            $rs[$k]['agent_level'] = strip_tags($this->c['agent_level'][$r['agent_level']]);

            if ($r['stat'] == 1) {

                $rs[$k]['stat'] = "正常";
            } else if ($r['stat'] == 2) {

                $rs[$k]['stat'] = "禁用";
            }
            if ($r['create_time'] > 0) {
                $rs[$k]['create_time'] = date("Y-m-d H:i", $r['create_time']);

            }

            $rs[$k]['level_time']      = "--";
            $rs[$k]['level_past_time'] = "--";
            if ($r['level_time'] > 0) {

                $rs[$k]['level_time'] = date("Y-m-d", $r['level_time']);
            }

            if ($r['level_past_time'] > 0) {

                $rs[$k]['level_past_time'] = date("Y-m-d", $r['level_past_time']);
            }
        }

        // 查询推荐人
        if ($pids) {
            $sql = "SELECT `uid`,`realname`,`recode` FROM {$this->_prefix['primary']}member_account WHERE `uid` IN (" . implode(",", $pids) . ")";
            $tmp = $this->sql($sql);
            if ($tmp) {
                foreach ($tmp as $r) {
                    $parents[$r['uid']] = $r;
                }
            }
        }

        if ($uids) {
            // 查询累积消费
            $sql = "SELECT SUM(`goods_amount`) AS `money`,`uid` FROM {$this->_prefix['primary']}order_info WHERE `uid` IN (" . implode(",", $uids) . ") AND `pay_status`=2 AND `order_status` IN (1,7) GROUP BY `uid`";
            $tmp = $this->sql($sql);
            if ($tmp) {
                foreach ($tmp as $r) {
                    $amount[$r['uid']] = $r['money'];
                }
            }

            // 查询用户资金
            $sql = "SELECT `uid`,`money`,`revenue`,`jifen` FROM {$this->_prefix['primary']}finance_balance WHERE `uid` IN (" . implode(",", $uids) . ")";
            //$sql = "SELECT `uid`,`money`,`revenue`,`sis_money`,`commission_jifen` FROM {$this->_prefix['primary']}finance_balance WHERE `uid` IN (" . implode(",", $uids) . ")";

            $tmp = $this->sql($sql);
            if ($tmp) {
                foreach ($tmp as $r) {
                    $balance[$r['uid']] = $r;
                }
            }

            // 查询推荐的会员人数
            $sql = "SELECT COUNT(`uid`) AS `cnt`,`pid` FROM {$this->_prefix['primary']}member_account WHERE `pid` IN (" . implode(",", $uids) . ") AND `stat`<3 GROUP BY `pid`";
            $tmp = $this->sql($sql);
            if ($tmp) {
                foreach ($tmp as $r) {
                    $child[$r['pid']] = $r['cnt'];
                }
            }

        }
        //print_r($child);die;
        return array(

            'data'    => $rs,
            'parents' => $parents,
            'amount'  => $amount,
            'balance' => $balance,
            'child'   => $child,

        );

    }

    //图片
    public function getPic($docid, $type = false)
    {
        if (is_array($docid)) {
            $where = " WHERE `docid` IN (" . implode(",", array_unique($docid)) . ")";
        } else {
            if (!$type) {
                $where = " WHERE `docid`=" . intval($docid);
            } else {

                $where = " WHERE `docid` IN (" . $docid . ")";
            }

        }

        $sql = "SELECT `docid`,`filename`,`create_time`,imgwh FROM {$this->_prefix['primary']}documents " . $where;
        $rs  = $this->sql($sql);
        if ($rs) {
            foreach ($rs as $k => $r) {
                $doc[$k]['img_url'] = $this->c['doc_host'] . date("Ymd", $r['create_time']) . "/" . date("H", $r['create_time']) . "/" . date("i", $r['create_time']) . "/" . $r['filename'];
                $doc[$k]['imgwh']   = $r['imgwh'];
            }
            return $doc;
        } else {
            return false;
        }

    }
    //会员收藏商品列表
    public function getCollection($para, $page = 1, $pagesize = 20)
    {

        $map = "  `state`=1";
        if ($para) {

            if (isset($para['uid'])) {
                $map .= " AND `uid`=" . $para['uid'];
            }
            if (isset($para['goods_id'])) {
                $map .= " AND `goods_id`=" . $para['goods_id'];
            }

        }
        // //会员条件查询

        $sql = "SELECT COUNT(`id`) AS `cnt` FROM {$this->_prefix['primary']}goods_collection WHERE " . $map;

        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`id` DESC";

            $sql = "SELECT * FROM {$this->_prefix['primary']}goods_collection WHERE " . $map . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;

            $rs = $this->sql($sql);

            if ($rs) {
                foreach ($rs as $k => $r) {
                    $uids[]      = $r['uid'];
                    $goods_ids[] = $r['goods_id'];
                }

                if ($uids) {
                    $sql    = "select uid,realname,headimgurl,wechat_headimgurl,member_level,mobile from mall_member_account where uid in(" . implode(',', $uids) . ")";
                    $member = $this->sql($sql);

                    $sql   = "select goods_id,goods_name,goods_sn,shop_price from mall_goods_data where goods_id in(" . implode(',', $goods_ids) . ")";
                    $goods = $this->sql($sql);

                }

                if ($member) {
                    foreach ($member as $r) {
                        if ($r['headimgurl'] > 0) {
                            $docid[] = $r['headimgurl'];
                        }

                    }

                    if ($docid) {
                        $docs = $this->getDocs($docid);
                    }

                }

                foreach ($rs as $k => $v) {
                    foreach ($member as $v1) {
                        if ($v['uid'] == $v1['uid']) {
                            $rs[$k]['realname']          = $v1['realname'];
                            $rs[$k]['headimgurl']        = $v1['headimgurl'];
                            $rs[$k]['wechat_headimgurl'] = $v1['wechat_headimgurl'];
                            if ($v1['member_level'] == 0 && $v1['mobile'] == "") {
                                $v1['member_level'] = -1;
                            }
                            $rs[$k]['member_level'] = $v1['member_level'];
                            $rs[$k]['mobile']       = $v1['mobile'];
                        }
                    }
                    foreach ($goods as $v2) {
                        if ($v['goods_id'] == $v2['goods_id']) {
                            $rs[$k]['goods_sn']   = $v2['goods_sn'];
                            $rs[$k]['goods_name'] = $v2['goods_name'];
                            $rs[$k]['shop_price'] = $v2['shop_price'];
                        }
                    }

                }

            }
//print_r($rs);die;
            return array(
                'page'    => $page,
                'maxpage' => ceil($cnt / $pagesize),
                'count'   => $cnt,
                'data'    => $rs,
                'para'    => $para,
                'docs'    => $docs,

            );
        }
    }

    //会员足迹商品列表
    public function gethistory($para, $page = 1, $pagesize = 20)
    {

        $map = " 1=1";
        if ($para) {

            if (isset($para['uid'])) {
                $map .= " AND `uid`=" . $para['uid'];
            }
            if (isset($para['goods_id'])) {
                $map .= " AND `goods_id`=" . $para['goods_id'];
            }

        }

        $sql = "SELECT COUNT(`id`) AS `cnt` FROM {$this->_prefix['primary']}goods_history WHERE " . $map;

        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`id` DESC";

            $sql = "SELECT * FROM {$this->_prefix['primary']}goods_history WHERE " . $map . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;

            $rs = $this->sql($sql);

            if ($rs) {
                foreach ($rs as $k => $r) {
                    $uids[]      = $r['uid'];
                    $goods_ids[] = $r['goods_id'];
                }

                if ($uids) {
                    $sql    = "select uid,realname,headimgurl,wechat_headimgurl,member_level,mobile from mall_member_account where uid in(" . implode(',', $uids) . ")";
                    $member = $this->sql($sql);
                    $sql    = "select goods_id,goods_name,goods_sn,shop_price from mall_goods_data where goods_id in(" . implode(',', $goods_ids) . ")";
                    $goods  = $this->sql($sql);

                }
                if ($member) {
                    foreach ($member as $r) {
                        if ($r['headimgurl'] > 0) {
                            $docid[] = $r['headimgurl'];
                        }

                    }

                    if ($docid) {
                        $docs = $this->getDocs($docid);
                    }

                }

                foreach ($rs as $k => $v) {
                    foreach ($member as $v1) {
                        if ($v['uid'] == $v1['uid']) {
                            $rs[$k]['realname']          = $v1['realname'];
                            $rs[$k]['headimgurl']        = $v1['headimgurl'];
                            $rs[$k]['wechat_headimgurl'] = $v1['wechat_headimgurl'];
                            if ($v1['member_level'] == 0 && $v1['mobile'] == "") {
                                $v1['member_level'] = -1;
                            }
                            $rs[$k]['member_level'] = $v1['member_level'];
                            $rs[$k]['mobile']       = $v1['mobile'];
                        }
                    }
                    foreach ($goods as $v2) {
                        if ($v['goods_id'] == $v2['goods_id']) {
                            $rs[$k]['goods_sn']   = $v2['goods_sn'];
                            $rs[$k]['goods_name'] = $v2['goods_name'];
                            $rs[$k]['shop_price'] = $v2['shop_price'];
                        }
                    }

                }

            }

        }
        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $rs,
            'para'    => $para,
            'docs'    => $docs,
        );
    }

    //保存用户
    public function saveMember($da, $uid)
    {
        $code         = 900;
        $password     = md5($da['password']);
        $stat         = intval($da['stat']);
        $member_level = intval($da['member_level']);
        $agent_level  = intval($da['agent_level']);
        $maker_level  = intval($da['maker_level']);
        $pid          = explode('-', $da['pid']);
        $parent_uid   = "";
        $sql          = "SELECT `uid`,`pass_rand`,`pid` FROM {$this->_prefix['primary']}member_account WHERE `uid`=" . intval($uid) . " AND `stat`<3";
        $rs           = $this->sql($sql);
        $m2           = intval($da['m2']);

        if ($rs) {

            if (!empty($pid[0]) && is_numeric($pid[0])) {

                $sql  = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE `uid`=" . $pid[0] . " AND `stat`<3";
                $data = $this->db->getrow($sql);
                if ($rs[0]['pid'] != $pid[0]) {
                    $parent_uid = ",pid=" . $pid[0];

                }
            }

            if ($stat == 2) {
                $sql = "DELETE FROM {$this->_prefix['primary']}member_online WHERE `uid`=" . $rs[0]['uid'];
                $rds = $this->sql($sql);
            }
            $pwd = "";
            if ($da['password'] != "") {
                $pwd = ",`password`='" . md5($password . $rs[0]['pass_rand']) . "'";
            }

            $sql = "UPDATE {$this->_prefix['primary']}member_account SET `m2`=" . $m2 . ",`stat`=" . $stat . ",`maker_level`=".$maker_level.",`agent_level`=" . $agent_level . ",`member_level`=" . $member_level . $parent_uid .$pwd. " WHERE `uid`=" . $rs[0]['uid'];
            $rd  = $this->sql($sql);

            if ($rd > 0) {

                $code = 200;

            } else {
                $code = 403;
            }
        }

        return $code;
    }

    //获取单个会员
    public function getSingleUser($uid, $getmore = true)
    {
        $sql  = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE `uid`=" . intval($uid) . " AND `stat`<3";
        $data = $this->db->getrow($sql);
        if ($data) {

            $data['balance'] = $this->db->getrow("SELECT * FROM {$this->_prefix['primary']}finance_balance WHERE `uid`=" . $data['uid']);

            if ($getmore) {

                if ($data['pid'] > 0) {

                    $sql            = "SELECT `uid`,`realname` FROM {$this->_prefix['primary']}member_account WHERE `uid`=" . $data['pid'];
                    $data['parent'] = $this->db->getrow($sql);
                }

            }

            return $data;
        }

    }

    // 获取系统所有注册会员
    public function getAllMember($para)
    {
        $where = " `stat`=1 ";
        if ($para['info']) {
            if (is_numeric($para['info'])) {

                $where .= " AND `recode`='" . $para['info'] . "'";
            } else {
                $where .= " AND (`realname` LIKE '%" . $para['info'] . "%')";

            }

            $sql = "SELECT `uid`,`realname` FROM {$this->_prefix['primary']}member_account WHERE " . $where;
            return $this->sql($sql);
        }

    }

    //获取搜索会员信息
    public function getDetailUser($uid, $type = false)
    {
        if ($type) {
            $where = " AND `uid` IN (" . $uid . ")";

        } else {

            $where = " AND `uid` = " . $uid;
        }
        $sql = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE stat <> 3" . $where;
        $rs  = $this->sql($sql);

        if ($rs) {
            foreach ($rs as $k => $r) {

                $uids[$r['uid']] = $r['uid'];

                if ($r['pid'] > 0) {
                    $pids[$r['pid']] = $r['pid'];
                }

                if ($r['headimgurl'] > 0) {
                    $pic                  = $this->getPic($r['headimgurl']);
                    $rs[$k]['headimgurl'] = $pic[0]['img_url'];
                }

                if ($r['store_id']) {
                    $store              = $this->getStore($r['store_id']);
                    $rs[$k]['store_id'] = $store['name'];
                }

                if ($r['member_level'] == 0 && $r['mobile'] == "") {
                    $rs[$k]['member_level'] = -1;
                }

            }

            if (!$type) {
                // 获取头像
                /*  if ($docids) {
                $docs = $this->getDocs($docids);
                } */
                // 查询推荐人
                if ($pids) {
                    $sql = "SELECT `uid`,`realname` FROM {$this->_prefix['primary']}member_account WHERE `uid` IN (" . implode(",", $pids) . ")";
                    $tmp = $this->sql($sql);
                    if ($tmp) {
                        foreach ($tmp as $r) {
                            $parents[$r['uid']] = stripslashes($r['realname']);
                        }
                    }
                }
                if ($uids) {
                    // 查询累积消费
                    $sql = "SELECT SUM(`goods_amount`) AS `money`,`uid` FROM {$this->_prefix['primary']}order_info WHERE `uid` IN (" . implode(",", $uids) . ") AND `pay_status`=2 AND `order_status` IN (1,7) GROUP BY `uid`";
                    $tmp = $this->sql($sql);
                    if ($tmp) {
                        foreach ($tmp as $r) {
                            $amount[$r['uid']] = $r['money'];
                        }
                    }

                    // 查询用户资金
                    $sql = "SELECT `uid`,`money`,`commission_jifen` FROM {$this->_prefix['primary']}finance_balance WHERE `uid` IN (" . implode(",", $uids) . ")";
                    $tmp = $this->sql($sql);
                    if ($tmp) {
                        foreach ($tmp as $r) {
                            $balance[$r['uid']] = $r;
                        }
                    }

                    // 查询推荐的会员人数
                    $sql  = "SELECT COUNT(`uid`) AS `cnt`,`pid` FROM {$this->_prefix['primary']}member_account WHERE `pid` IN (" . implode(",", $uids) . ") AND `stat`<3 GROUP BY `pid`";
                    $tmps = $this->sql($sql);
                    if ($tmps) {
                        foreach ($tmps as $r) {
                            $child[$r['pid']] = $r['cnt'];
                        }
                    }
                }

                $sql    = "SELECT * FROM {$this->_prefix['primary']}member_wechat WHERE `uid`=" . $uid;
                $wechat = $this->db->getrow($sql);
            }
            return array(
                'data'    => $rs,
                'parents' => $parents,
                'amount'  => $amount,
                'balance' => $balance,
                'docs'    => $docs,
                'child'   => $child,
                'wechat'  => $wechat,
            );

        }

    }

    //获取会员信息
    public function getSingleMember($uid)
    {
        $uid = intval($uid);
        $sql = "SELECT * from {$this->_prefix['primary']}member_account where uid=" . $uid;
        return $this->db->getrow($sql);

    }

    //搜索会员信息
    public function getSearchMember($search)
    {
        $arr         = array();
        $arr['code'] = 900;
        $arr['msg']  = "未搜到用户!";
        $search      = addslashes(htmlspecialchars(trim($search)));
        if (!empty($search)) {

            $where = "realname LIKE '%" . $search . "%' OR mobile = '" . $search . "'";
            $sql   = "SELECT * from {$this->_prefix['primary']}member_account where " . $where;
            $users = $this->sql($sql);
            //print_r(count($users));die;
            if ($users) {
                $ids = '';
                if (count($users) > 1) {
                    foreach ($users as $val) {
                        $ids .= empty($ids) ? $val['uid'] : ',' . $val['uid'];
                    }
                    $us          = $this->getDetailUser(trim($ids), true);
                    $arr['code'] = 200;
                    $arr['uid']  = $ids;
                    $arr['type'] = true;
                    $arr['data'] = $us;
                } else {
                    $arr['code'] = 200;
                    $arr['uid']  = $users[0]['uid'];
                    $arr['type'] = false;
                }

            }
        } else {
            $arr['code'] = 901;
            $arr['msg']  = "搜索不能为空!";
        }
        return $arr;

    }

    // 充值
    public function saveRecharge($da)
    {

        $code         = 900;
        $uid          = intval($da['uid']);
        $gold_money   = intval($da['number']);
        $ximi_money   = intval($da['ximi_number']);
        $ticket_money = intval($da['ticket_number']);
        $coupon       = intval($da['coupon_number']);

        $comments1 = addslashes(htmlspecialchars(trim($da['comments1'])));
        $comments2 = addslashes(htmlspecialchars(trim($da['comments2'])));
        $comments3 = addslashes(htmlspecialchars(trim($da['comments3'])));
        $comments4 = addslashes(htmlspecialchars(trim($da['comments4'])));

        if ($uid > 0) {

            $sql     = "SELECT * FROM {$this->_prefix['primary']}finance_balance WHERE `uid`=" . $uid;
            $balance = $this->db->getrow($sql);

            if ($balance) {

                // 充值金花
                if ($gold_money != 0) {

                    // 执行充值
                    $this->db->begin();
                    $commit = false;
                    $code   = 403;

                    $sql = "UPDATE {$this->_prefix['primary']}finance_balance SET `gold_money`=`gold_money`+" . $gold_money . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . ",`last_aid`=" . $this->_auth['aid'] . ",`last_edit`='" . $_SERVER['REQUEST_TIME'] . "' WHERE `uid`=" . $balance['uid'];

                    $rcb = $this->sql($sql);

                    if ($rcb > 0) {
                        // 插入明细
                        //
                        $detail_note = '后台充值金花成功';
                        $event       = 1;
                        $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`dataid`,`table_name`,`create_time`,`note`,`last_aid`,`last_edit`,`comments`) VALUES (" . $balance['uid'] . "," . $event . "," . $gold_money . "," . ($balance['gold_money'] + $gold_money) . "," . $balance['uid'] . ",'finance_balance'," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "'," . $this->_auth['aid'] . ",'" . $_SERVER['REQUEST_TIME'] . "','" . $comments1 . "')";
                        $detail_id   = $this->sql($sql);
                        if ($detail_id > 0) {

                            $code   = 200;
                            $commit = true;
                        }
                    }

                    if ($commit) {
                        $this->db->commit();
                    } else {
                        $this->db->rollback();
                    }
                }

                // 充值硒米
                if ($ximi_money != 0) {

                    // 执行充值
                    $this->db->begin();
                    $commit = false;
                    $code   = 403;

                    $sql = "UPDATE {$this->_prefix['primary']}finance_balance SET `ximi_money`=`ximi_money`+" . $ximi_money . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . ",`last_aid`=" . $this->_auth['aid'] . ",`last_edit`='" . $_SERVER['REQUEST_TIME'] . "' WHERE `uid`=" . $balance['uid'];

                    $rcb = $this->sql($sql);

                    if ($rcb > 0) {

                        // 插入明细
                        $detail_note = '后台充值硒米成功';
                        $event       = 2;
                        $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`dataid`,`table_name`,`create_time`,`note`,`last_aid`,`last_edit`,`comments`) VALUES (" . $balance['uid'] . "," . $event . "," . $ximi_money . "," . ($balance['ximi_money'] + $ximi_money) . "," . $balance['uid'] . ",'finance_balance'," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "'," . $this->_auth['aid'] . ",'" . $_SERVER['REQUEST_TIME'] . "','" . $comments2 . "')";
                        $detail_id   = $this->sql($sql);
                        if ($detail_id > 0) {

                            $code   = 200;
                            $commit = true;
                        }
                    }

                    if ($commit) {
                        $this->db->commit();
                    } else {
                        $this->db->rollback();
                    }
                }

                // 充值商品票
                if ($ticket_money != 0) {

                    // 执行充值
                    $this->db->begin();
                    $commit = false;
                    $code   = 403;

                    $sql = "UPDATE {$this->_prefix['primary']}finance_balance SET `ticket`=`ticket`+" . $ticket_money . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . ",`last_aid`=" . $this->_auth['aid'] . ",`last_edit`='" . $_SERVER['REQUEST_TIME'] . "' WHERE `uid`=" . $balance['uid'];

                    $rcb = $this->sql($sql);

                    if ($rcb > 0) {

                        // 插入明细
                        $detail_note = '后台充值商品票成功';
                        $event       = 10;
                        $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`dataid`,`table_name`,`create_time`,`note`,`last_aid`,`last_edit`,`comments`) VALUES (" . $balance['uid'] . "," . $event . "," . $ticket_money . "," . ($balance['ticket'] + $ticket_money) . "," . $balance['uid'] . ",'finance_balance'," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "'," . $this->_auth['aid'] . ",'" . $_SERVER['REQUEST_TIME'] . "','" . $comments4 . "')";
                        $detail_id   = $this->sql($sql);
                        if ($detail_id > 0) {

                            $code   = 200;
                            $commit = true;
                        }
                    }

                    if ($commit) {
                        $this->db->commit();
                    } else {
                        $this->db->rollback();
                    }
                }

                // 充值代金券
                if ($coupon != 0) {

                    // 执行充值
                    $this->db->begin();
                    $commit = false;
                    $code   = 403;

                    $sql = "UPDATE {$this->_prefix['primary']}finance_balance SET `coupon`=`coupon`+" . $coupon . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . ",`last_aid`=" . $this->_auth['aid'] . ",`last_edit`='" . $_SERVER['REQUEST_TIME'] . "' WHERE `uid`=" . $balance['uid'];

                    $rcb = $this->sql($sql);

                    if ($rcb > 0) {

                        // 插入明细
                        $detail_note = '后台充值代金券成功';
                        $event       = 11;
                        $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`dataid`,`table_name`,`create_time`,`note`,`last_aid`,`last_edit`,`comments`) VALUES (" . $balance['uid'] . "," . $event . "," . $coupon . "," . ($balance['coupon'] + $coupon) . "," . $balance['uid'] . ",'finance_balance'," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "'," . $this->_auth['aid'] . ",'" . $_SERVER['REQUEST_TIME'] . "','" . $comments3 . "')";
                        $detail_id   = $this->sql($sql);
                        if ($detail_id > 0) {

                            $code   = 200;
                            $commit = true;
                        }
                    }

                    if ($commit) {
                        $this->db->commit();
                    } else {
                        $this->db->rollback();
                    }
                }

            } else {
                $code = 404;
            }
        }

        return $code;

    }

    // 获取设置
    public function getSetting()
    {
        $sql     = "SELECT `setting` FROM {$this->_prefix['primary']}setting ORDER BY `setting_id` DESC LIMIT 1";
        $setting = $this->db->getone($sql);
        if ($setting != "") {
            return json_decode($setting, true);
        }

    }

}
